from socketio import AsyncServer
from core.logger import log
from services.gridfs_service import get_image_bytes_or_base64
from utils.minio_util import put_image


async def broadcast_message(sio: AsyncServer,message_data: dict, room: str = None):
    """
    广播消息给 WebSocket 客户端
    :param message_data: 要发送的消息数据
    :param room: 可选的房间名，如果指定则只发送给该房间的客户端
    """
    try:
        if room:
            await sio.emit('new_message', message_data, room=room)
        else:
            await sio.emit('new_message', message_data)
        log.info(f"消息已广播到 WebSocket: {message_data},房间room是：{room}")
    except Exception as e:
        log.error(f"广播消息失败: {e}")


async def download_image(key, from_user, msg_id, to_user,minio_client):
    """
    将微信消息的图片进行下载
    下载微信图片并上传到 MinIO
    :param key: 用户的token_key
    :param from_user: 图片发送者的用户名
    :param msg_id: 图片消息的 ID
    :param to_user: 图片接收者的用户名
    :return: 图片的 URL
    """
    try:
        parm_data = {
            "Key": key,
            "FromUserName": from_user,
            "MsgId": msg_id,
            "ToUserName": to_user
        }
        complete_binary = await get_image_bytes_or_base64(parm_data)
        image_url = await put_image(complete_binary, parm_data["MsgId"], minio_client=minio_client)
        return image_url
    except Exception as e:
        log.error(f"下载图片并上传到 MinIO 失败: {e}")
        return None




